package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

    private static Logger logger=Logger.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    /**
     * 跳转到登录页面的处理器
     * @return 登录页面名称
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 处理登录的方法
     * @param userCode
     * @param userPassword
     * @return
     */
    @RequestMapping(value = "/doLogin",method = RequestMethod.POST)
    public String doLogin(@RequestParam(value = "userCode",required = false)String userCode,
                          @RequestParam(value = "userPassword",required = false)String userPassword,
                          HttpServletRequest request){
        logger.info("================DoLogin================");
        logger.info("userCode:"+userCode);
        logger.info("userPassword:"+userPassword);
        logger.info("=======================================");

        User user = userService.login(userCode, userPassword);


        if (user == null) {
            request.setAttribute("error", "用户名或密码不正确！");

            return "login";
        }

        request.getSession().setAttribute(Constants.USER_SESSION, user);

        return "frame";
    }

    @RequestMapping(value = "/homePage")
    public String homePage(){
        return "frame";
    }

    @RequestMapping(value = "loginOut")
    public String loginOut(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);

        return "redirect:toLogin";
    }


    @RequestMapping(value = "/list")
    public String getUserList(@RequestParam(value = "queryUserName",required = false)String queryUserName,
                              @RequestParam(value ="pageIndex",required = false)String currPageNoStr,
                              @RequestParam(value = "queryUserRole",required = false)String queryUserRole,
                              HttpServletRequest request){

        Integer userRole=null;

        if (queryUserRole != null) {
            userRole=Integer.valueOf(queryUserRole);
        }else {
            userRole=0;
        }

        //获取总记录数
        int totalCount=userService.getUserCount(queryUserName, userRole);

        PageSupport pageSupport=new PageSupport();
        pageSupport.setTotalCount(totalCount);

        pageSupport.setCurrentPageNo(currPageNoStr==null?1:Integer.valueOf(currPageNoStr));

        //获取所有角色信息
        List<Role> roleList=roleService.getRoleList();

        pageSupport.setList(userService.getUserList(queryUserName, userRole, pageSupport.getCurrentPageNo(),pageSupport.getPageSize()));

        request.setAttribute("pageObj", pageSupport);
        request.setAttribute("roleList", roleList);

        return "userlist";
    }

    @RequestMapping(value = "/useradd",method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user")User user){
        return "useradd";
    }

    @RequestMapping(value = "/addsave",method = RequestMethod.POST)
    public String addUserSave(User user,
                              HttpSession session,
                              HttpServletRequest request,
                              @RequestParam(value = "attachs",required = false)MultipartFile[]attachs){

        String errorInfo=null;
        boolean flag=true;

        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach=attachs[i];
            //判断文件是否为空
            if (!attach.isEmpty()){
                String path=request.getSession().getServletContext().getRealPath("static"+ File.separator+"uploadfile");
                logger.info("uploadFile Path==============>"+path);

                String oldFileName=attach.getOriginalFilename();//获取源文件名
                logger.debug("uploadFile oldFileName==========>"+oldFileName);

                String suffix= FilenameUtils.getExtension(oldFileName).toLowerCase();//获取原文件后缀
                logger.debug("uploadFile suffix=============>"+suffix);

                int filesize=500000;
                logger.debug("uploadFile filesize=============>"+attach.getSize()+"byte");

                if(attach.getSize()>filesize){ //上传文件不得大于500kb
                    request.setAttribute("uploadFileError", "* 上传大小不得超过500KB");
                   flag=false;
                }else if (suffix.equalsIgnoreCase("jpg")||
                        suffix.equalsIgnoreCase("png")||
                        suffix.equalsIgnoreCase("jpeg")||
                        suffix.equalsIgnoreCase("pneg")){//上传格式是否正确
                    String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1,1000000)+"_Personal.jpg";

                    File targetFile=new File(path,fileName);

                    if(!targetFile.exists()){
                        targetFile.mkdirs();//创建当前文件/目录及其所需父级目录
                    }

                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute("uploadError", "* 上传失败！");
                        flag=false;
                    }

                    if(i==0){
                        user.setIdPicPath(path+File.separator+fileName);
                    }else if (i==1){
                        user.setWorkPicPath(path+File.separator+fileName);
                    }
                }else{
                    request.setAttribute("uploadError", "* 上传图片格式不正确");
                    flag=false;
                }
            }
        }

        if (flag){
            user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
            user.setCreationDate(new Date());

            if(userService.add(user)>0){
                return "redirect:/user/list";
            }
        }

        return "useradd";
    }

    @RequestMapping("/ucexist")
    @ResponseBody
    public Object checkUserCode(@RequestParam(value = "userCode")String userCode, HttpServletResponse response){
        logger.debug("userCodeIsExist userCode:"+userCode);

        HashMap<String,String> resultMap=new HashMap<String,String>();

        if (StringUtils.isNullOrEmpty(userCode)){//判断字符串是否为空
            resultMap.put("userCode", "exist");
        }else {
            User user=userService.selectUserCodeExist(userCode);

            if (user != null) {
                resultMap.put("userCode", "exist");
            }else{
                resultMap.put("userCode", "noexists");
            }
        }

        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "/useradd2",method = RequestMethod.GET)
    public String addUser2(@ModelAttribute("user")User user){
        return "useradd2";
    }

    @RequestMapping(value = "/useradd2",method = RequestMethod.POST)
    public String addSave2(@Valid User user, BindingResult bindingResult, HttpSession session){

        if (bindingResult.hasErrors()){
            logger.debug("add user validated has error======================");

            return "useradd2";
        }

        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());

        if(userService.add(user)>0){
            return "redirect:/user/list";
        }

        return "useradd2";
    }

    @RequestMapping(value = "/usermodify",method = RequestMethod.GET)
    public String getUserById(@RequestParam(value = "uid")String uid, Model model){
        logger.debug("getUserById uid=========="+uid);

        User user=userService.getUserById(uid);

        model.addAttribute(user);

        return "usermodify";
    }

    @RequestMapping(value = "/usermodifysave",method = RequestMethod.POST)
    public String modifyUserSave(User user,HttpSession session){
        logger.debug("modifyUserSave userid============"+user.getId());

        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        if (userService.modify(user)){
            return "redirect:/user/list";
        }

        return "usermodify";
    }

    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String showDetail(@PathVariable String id, Model model){
        logger.debug("showDetail id================"+id);

        User user=userService.getUserById(id);
        model.addAttribute(user);

        return "userview";
    }

    @RequestMapping(value = "/view",method = RequestMethod.GET)
    @ResponseBody
    public User view(@RequestParam(value = "id")String id){
        logger.debug("view id:"+id);

        String cjson="";

        User user=new User();

        try {
            user=userService.getUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }

    @RequestMapping(value = "/modifypwd")
    public String toModifyPwd(){
        return "pwdmodify";
    }

    @RequestMapping(value = "/doModifyPwd",method = RequestMethod.POST)
    public String doModifyPwd(@RequestParam(value = "newpassword")String password,
                              @RequestParam(value = "rnewpassword")String rpassword,
                              HttpServletRequest request){

        User user=(User) request.getSession().getAttribute(Constants.USER_SESSION);

        if(user==null){
            return "redirect:/user/toLogin";
        }else if (password.equals(rpassword)) {
            if(userService.updatePwd(user.getId(), password)){
                return "redirect:/user/loginOut";
            }else{
                return "redirect:/user/toModifyPwd";
            }
        }

        return "redirect:/user/toModifyPwd";
    }

    @RequestMapping(value = "checkPwd.json",method = RequestMethod.GET)
    @ResponseBody
    public Object checkPwd(@RequestParam(value = "oldpassword")String oldPassword,HttpServletRequest request){
        User user=(User)request.getSession().getAttribute(Constants.USER_SESSION);

        HashMap<String,String> resultMap=new HashMap<String, String>();


        if (user == null) {
            resultMap.put("result", "sessionerror");
        }else if(oldPassword==null){
            resultMap.put("result", "error");
        }else if (user.getUserPassword().equals(oldPassword)) {
            resultMap.put("result", "true");
        }else{
            resultMap.put("result", "false");
        }

        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delUser(@RequestParam(value = "uid")Integer uId){

        HashMap<String,String> delResultMap=new HashMap<String, String>();

        if (uId == null) {
            delResultMap.put("delResult", "notexist");
        }else if(userService.getUserById(uId.toString())==null){
            delResultMap.put("delResult", "notexist");
        }else{
            delResultMap.put("delResult", userService.deleteUserById(uId)+"");
        }

        return JSONArray.toJSONString(delResultMap);
    }
}
